define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    var Controller = {
        index: function () {
            // 初始化分配管理
            var allocations = [];
            var planId = null;
            var totalQuantity = 0;
            var allocatedQuantity = 0;
            
            // 从页面获取数据
            function initData() {
                planId = $('input[name="plan_id"]').val() || $('.plan-info').data('plan-id');
                totalQuantity = parseInt($('.plan-info').data('total-quantity')) || 0;
                allocatedQuantity = parseInt($('.plan-info').data('allocated-quantity')) || 0;
            }
            
            // 添加工序到分配列表
            $(document).on('click', '.add-process', function() {
                var processId = $(this).data('process-id');
                var processName = $(this).data('process-name');
                
                // 检查是否已经添加过这个工序
                if (allocations.find(a => a.process_id == processId)) {
                    alert('该工序已经添加过了！');
                    return;
                }
                
                // 创建分配项
                var allocation = {
                    process_id: processId,
                    process_name: processName,
                    workers: []
                };
                
                allocations.push(allocation);
                updateAllocationList();
                updateSaveButton();
            });
            
            // 更新分配列表显示
            function updateAllocationList() {
                var html = '';
                if (allocations.length === 0) {
                    html = '<p class="text-muted">暂无分配，请从左侧选择工序</p>';
                } else {
                    allocations.forEach(function(allocation, index) {
                        html += `
                            <div class="panel panel-default allocation-panel" data-index="${index}">
                                <div class="panel-heading">
                                    <h5 class="panel-title">${allocation.process_name}</h5>
                                </div>
                                <div class="panel-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <label>分配工人：</label>
                                            <select class="form-control worker-select" data-allocation-index="${index}">
                                                <option value="">请选择工人</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <label>分配数量：</label>
                                            <input type="number" class="form-control quantity-input" data-allocation-index="${index}" min="1" max="${totalQuantity - allocatedQuantity}">
                                        </div>
                                        <div class="col-md-2">
                                            <label>&nbsp;</label>
                                            <button type="button" class="btn btn-danger btn-sm remove-allocation" data-allocation-index="${index}">删除</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                }
                $('#allocation-list').html(html);
                
                // 填充工人选项
                fillWorkerOptions();
            }
            
            // 填充工人选项
            function fillWorkerOptions() {
                $('.worker-select').each(function() {
                    var $select = $(this);
                    var currentValue = $select.val();
                    $select.empty().append('<option value="">请选择工人</option>');
                    
                    // 从页面获取工人列表
                    $('.worker-option').each(function() {
                        var value = $(this).val();
                        var text = $(this).text();
                        $select.append(`<option value="${value}">${text}</option>`);
                    });
                    
                    $select.val(currentValue);
                });
            }
            
            // 删除分配项
            $(document).on('click', '.remove-allocation', function() {
                var index = $(this).data('allocation-index');
                allocations.splice(index, 1);
                updateAllocationList();
                updateSaveButton();
            });
            
            // 更新保存按钮显示
            function updateSaveButton() {
                if (allocations.length > 0) {
                    $('#save-allocations').show();
                } else {
                    $('#save-allocations').hide();
                }
            }
            
            // 保存分配
            $('#save-allocations').click(function() {
                var validAllocations = [];
                var totalAllocated = 0;
                
                // 验证所有分配
                $('.allocation-panel').each(function() {
                    var index = $(this).data('index');
                    var workerId = $(this).find('.worker-select').val();
                    var quantity = parseInt($(this).find('.quantity-input').val()) || 0;
                    
                    if (workerId && quantity > 0) {
                        validAllocations.push({
                            process_id: allocations[index].process_id,
                            user_id: workerId,
                            quantity: quantity
                        });
                        totalAllocated += quantity;
                    }
                });
                
                if (validAllocations.length === 0) {
                    alert('请至少完成一个分配！');
                    return;
                }
                
                if (totalAllocated > totalQuantity) {
                    alert('分配数量不能超过计划数量！');
                    return;
                }
                
                // 提交数据
                $.post(Backend.api.fixurl('scanwork/production_plan/saveBatchAllocate'), {
                    plan_id: planId,
                    allocations: validAllocations
                }, function(result) {
                    if (result.code === 1) {
                        alert('分配保存成功！');
                        location.reload();
                    } else {
                        alert('保存失败：' + result.msg);
                    }
                }, 'json');
            });
            
            // 初始化
            initData();
        }
    };
    return Controller;
});
